package com.gupaoedu.baifc.staticproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * projectName: baifc_proxy
 * packageName: com.gupaoedu.baifc.staticproxy
 * Created: 2019/3/18.
 * Auther: baifc
 * Description:
 */
public class OrderServiceDynamicProxy implements InvocationHandler {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy");


    private Object target;

    public Object getInstance(Object target) {
        this.target = target;

        Class clazz = target.getClass();

        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);

    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Date createTime = (Date) args[0].getClass().getMethod("getCreateTime").invoke(args[0]);

        int year = Integer.parseInt(sdf.format(createTime));

        DynamicDataSourceEntry.set(year);
        System.out.println("数据源已切换到【DB_" + year + "】");
        Object obj = method.invoke(target, args);
        return obj;
    }
}
